package com.example.changtest.util

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.example.changtest.cockroach.Cockroach
import java.lang.Exception

/**
 * @Description: 异常处理
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/1/24 12:58
 */
class CrashHandler private constructor() : Thread.UncaughtExceptionHandler{
    private var context: Context? = null
    fun init(context: Context?) {
        this.context = context
        Thread.setDefaultUncaughtExceptionHandler(this)
    }
    companion object{
        val instance : CrashHandler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { CrashHandler() }
    }

    override fun uncaughtException(t: Thread, e: Throwable) {
        if (t === Looper.getMainLooper().thread) {
            //Toast.makeText(context, "主线程出现错误：" + e.message, Toast.LENGTH_SHORT).show()
            Log.e("error","主线程出现错误：" + e?.message)
            while (true) {
                try {
                    Looper.loop()
                } catch (e1: Throwable) {
                    Log.e("error","Throwable 主线程出现错误：" + e1?.message)
                }
            }
        }
//        else {
//            Handler(Looper.getMainLooper()).post {
//                Toast.makeText(context,
//                    "子线程出现错误：" + e.message,
//                    Toast.LENGTH_SHORT).show()
//            }
//        }


    }

    /**
     * view measure layout draw时抛出异常会导致Choreographer挂掉
     *
     *
     * 建议直接杀死app。以后的版本会只关闭黑屏的Activity
     *
     * @param e
     */
    private fun isChoreographerException(e: Throwable?) {
        if (e == null) {
            return
        }
        val elements = e.stackTrace ?: return
        for (i in elements.size - 1 downTo -1 + 1) {
            if (elements.size - i > 20) {
                return
            }
            val element = elements[i]
            if ("android.view.Choreographer" == element.className && "Choreographer.java" == element.fileName && "doFrame" == element.methodName) {
                //Cockroach.sExceptionHandler.mayBeBlackScreen(e)
                //黑屏时建议直接杀死app
                return
            }
        }
    }
}